package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.common.Utils;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;

/**
 * Proceess escaped chars and hardbreaks
 * @author liuqianfei
 */
public class EscapeAction implements IAction
{
    char[] ESCAPED = new char[256];

    private void setUp()
    {
        String[] data = "\\!\"#$%&\'()*+,./:;<=>?@[]^_`{|}~-".split("");
        for (String ch : data)
        {
            ESCAPED[ch.charAt(0)] = 1;
        }
    }

    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        setUp();

        char ch;
        int pos = state.getPos(), max = state.getPosMax();

        if (state.getSrc().charAt(pos) != 0x5C/* \ */)
            return false;

        pos++;

        if (pos < max)
        {
            ch = state.getSrc().charAt(pos);

            if (ch < 256 && ESCAPED[ch] != 0)
            {
                if (!silent)
                    state.setPending(state.getPending() + state.getSrc().charAt(pos));
                state.setPos(state.getPos() + 2);
                return true;
            }

            if (ch == 0x0A)
            {
                if (!silent)
                {
                    state.push("hardbreak", "br", 0);
                }

                pos++;
                // skip leading whitespaces from next line
                while (pos < max)
                {
                    ch = state.getSrc().charAt(pos);
                    if (!Utils.isSpace(ch))
                        break;
                    pos++;
                }

                state.setPos(pos);
                return true;
            }
        }

        if (!silent)
            state.setPending(state.getPending() + "\\");

        state.setPos(state.getPos() + 1);
        return true;
    }
}
